package com.yinsw.config;

import com.alibaba.fastjson.JSONObject;
import com.yinsw.dao.HouseDao;
import com.yinsw.entity.HouseEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author printguy
 * @version 1.0.0
 * @className HouseEsSync.java
 * @description TODO
 * @createTime 2022年07月19日 15:21:00
 */
@Component
public class HouseEsSync implements ApplicationRunner {

    private final HouseDao houseDao;
    private final RestHighLevelClient client;

    public HouseEsSync(HouseDao houseDao, RestHighLevelClient client) {
        this.houseDao = houseDao;
        this.client = client;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<HouseEntity> houseEntityList = houseDao.selectList(null);
        BulkRequest bulkRequest = new BulkRequest("house");
        houseEntityList.forEach(houseEntity->{
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(houseEntity.getId().toString());
            String equipment = houseEntity.getEquipment();
            if (equipment!=null){
                houseEntity.setEquipments(equipment.split(","));
            }
            String tag = houseEntity.getTag();
            if (tag!=null){
                houseEntity.setTags(tag.split(","));
            }
            String industry = houseEntity.getIndustry();
            if (industry!=null){
                houseEntity.setIndustrys(industry.split(","));
            }
            String feature = houseEntity.getFeature();
            if (feature!=null){
                houseEntity.setFeatures(feature.split(","));
            }
            String consumer = houseEntity.getConsumer();
            if (consumer!=null){
                houseEntity.setConsumers(consumer.split(","));
            }
            indexRequest.source(JSONObject.toJSONString(houseEntity), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
